package mid

import (
	"encoding/json"
	app "gitee.com/zmhfly8/gm/pkg/app"
	errcode "gitee.com/zmhfly8/gm/pkg/errcode"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"strings"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token string
			ecode = errcode.Success
		)
		if token = c.GetHeader("Authorization"); "" != token {
			// 截取 Bearer 后的数据
			token = strings.TrimSpace(strings.TrimPrefix(token, "Bearer"))
		} else {
			s, exist := c.GetQuery("token")
			if !exist {
				response := app.Response{
					Ctx: c,
				}
				response.ToError(errcode.ErrorMemberLogin)
				c.Abort()
				return
			}
			token = s
		}
		if token == "" {
			ecode = errcode.UnauthorizedTokenError
		} else {
			td, err := app.ParseToken(token)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					ecode = errcode.UnauthorizedTokenTimeout
				default:
					ecode = errcode.UnauthorizedTokenError
				}
			}
			var tdjson []byte
			tdjson, err = json.Marshal(td)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					ecode = errcode.UnauthorizedTokenTimeout
				default:
					ecode = errcode.UnauthorizedTokenError
				}
			}
			c.Set("loginUser", string(tdjson))
		}

		if ecode != errcode.Success {
			response := app.Response{Ctx: c}
			response.ToError(errcode.ToLogin)
			c.Abort()
			return
		}

		c.Next()
	}
}
